//
//  BookInfoViewController.m
//  ZYTS-iPhone
//
//  Created by yuzhou on 12-12-9.
//  Copyright (c) 2012年 wzyk. All rights reserved.
//

#import "ListenDetailViewController.h"
#import "UIImageView+WebCache.h"
//#import "AuthorManager.h"
//#import "AccountViewController.h"
//#import "ShareViewController.h"
#import <QuartzCore/QuartzCore.h>
//#import "SinaWeiboManager.h"
#import "DataBase.h"

@interface ListenDetailViewController ()

@end

@implementation ListenDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotListenContent:) name:kNotifyGotListenContent object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self showLoadingView];
    
    coverImageView.layer.shadowColor = [UIColor blackColor].CGColor;
    coverImageView.layer.shadowOpacity = 0.45f;
    coverImageView.layer.shadowOffset = CGSizeMake(0, 3);
    coverImageView.layer.masksToBounds = NO;
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:coverImageView.bounds];
    coverImageView.layer.shadowPath = path.CGPath;
    
    [self getData];
}

- (void)getData
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary *data = [[DataRequest sharedRequest] getListenInfo:_listenID];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data && [data isKindOfClass:[NSDictionary class]] && [[data objectForKey:@"result"] isKindOfClass:[NSDictionary class]]) {
                self.listenInfo = [data objectForKey:@"result"];
                [self updateDetail];
//                [[NSNotificationCenter defaultCenter] postNotificationName:kNotifyGotListenInfo object:_listenInfo];
            }
        });
    });
}

- (void)updateDetail
{
    [self removeloadingView];
    NSString *imageURL = [[self.listenInfo valueForKey:@"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [coverImageView setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"default_image"] options:SDWebImageRetryFailed];
    artistLabel.text = [self.listenInfo valueForKey:@"broadcaster"];
    chapterLabel.text = [NSString stringWithFormat:@"%@",[self.listenInfo valueForKey:@"sub_count"]];
    sharedLabel.text = [NSString stringWithFormat:@"%@",[self.listenInfo valueForKey:@"share_count"]];
    collectedLabel.text = [NSString stringWithFormat:@"%@",[self.listenInfo valueForKey:@"favorite_count"]];
    commentedLabel.text = [NSString stringWithFormat:@"%@",[self.listenInfo valueForKey:@"comment_count"]];
    [self setRate:[[self.listenInfo valueForKey:@"item_rank"] intValue]];
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<.*>"
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:nil];
    NSString *description = [self.listenInfo valueForKey:@"description"];
    if (description) {
        description = [regex stringByReplacingMatchesInString:description options:0 range:NSMakeRange(0, [description length]) withTemplate:@""];
        descriptionTextView.text = description;
    }
    
    shareButton.enabled = YES;
    [shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [[DataBase shareDB] addListen:[_listenInfo objectForKey:@"item_id"] cover:[_listenInfo objectForKey:@"image"]];
}

- (void)setRate:(int)rate
{
    rateLabel.text = [NSString stringWithFormat:@"%d分",rate];
    for (int i = 0; i < 5; i++) {
        UIImageView *starView = (UIImageView *)[[rateView subviews] objectAtIndex:i];
        if (i * 2 + 2 <= rate) {
            starView.image = [UIImage imageNamed:@"fullStar.png"];
        }
        else if (i * 2 + 1 <= rate) {
            starView.image = [UIImage imageNamed:@"halfStar.png"];
        }
        else {
            starView.image = [UIImage imageNamed:@"emptyStar.png"];
        }
    }
    rateView.hidden = NO;
}

- (void)collectBook:(NSNotification *)notification {
//    [[[[UIAlertView alloc] initWithTitle:nil
//                                 message:[[[notification object] objectForKey:@"result"] objectForKey:@"state_message"]
//                                delegate:nil
//                       cancelButtonTitle:@"确定"
//                       otherButtonTitles:nil] autorelease] show];
    
//    ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:[[[notification object] objectForKey:@"result"] objectForKey:@"state_message"]] autorelease];
//    [promptView show];
}

- (void)gotListenContent:(NSNotification *)notification
{
    if ([notification.object isKindOfClass:[NSArray class]]) {
        NSArray *result = [notification.object valueForKey:@"result"];
        if ([result isKindOfClass:[NSArray class]]) {
            self.contentArray = result;
            downloadButton.enabled = YES;
            [downloadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
}

- (IBAction)downloadAction:(id)sender
{
//    if (![[AuthorManager defaultManager] hasLoggedIn]) {
//        AccountViewController *accountViewController = [[[AccountViewController alloc] initWithNibName:@"AccountViewController" bundle:nil] autorelease];
//        accountViewController.needLogin = YES;
//        [self.view.window.rootViewController presentViewController:accountViewController animated:YES completion:nil];
//        return;
//    }
//    else if (![[AuthorManager defaultManager] hasUserPaid]) {
//        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"183read.com" message:@"离线功能仅限中邮阅读网付费用户" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil] autorelease];
//        [alertView show];
//        return;
//    }
//    if (![[DownloadManager defaultManager] isConnectionEnable]) {
//        ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"无网络连接"] autorelease];
//        [promptView show];
//        return;
//    }
//    else if ([[DownloadManager defaultManager] isWWANEnable]) {
//        if (![[DownloadManager defaultManager] WWANDownloadEnable]) {
//            UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"当前为2G/3G网络" message:@"您可在设置中允许使用2G/3G网络" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"仍然下载", nil] autorelease];
//            [alertView show];
//        }
//        return;
//    }
//    for (NSDictionary *content in self.contentArray) {
//        [[DownloadManager defaultManager] downloadBook:content];
//    }
//    ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"已加入下载列表"] autorelease];
//    [promptView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    if (buttonIndex == 1) {
//        for (NSDictionary *content in self.contentArray) {
//            [[DownloadManager defaultManager] downloadBook:content];
//        }
//        ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"已加入下载列表"] autorelease];
//        [promptView show];
//    }
}

- (IBAction)onClickShareBtn:(id)sender {
//    if ([[[SinaWeiboManager defaultManager] sinaweibo] isLoggedIn]) {
//        ShareViewController *shareViewController = [[[ShareViewController alloc] initWithNibName:@"ShareViewController" bundle:nil] autorelease];
//        shareViewController.info = _bookInfo;
//        shareViewController.shareType = ShareTypeSinaWeibo;
//        UINavigationController *navController = (UINavigationController *)self.view.window.rootViewController;
//        [navController pushViewController:shareViewController animated:YES];
//    } else {
//        [[[SinaWeiboManager defaultManager] sinaweibo] logIn];
//    }
}

- (IBAction)onClickCollectBtn:(id)sender {
//    if ([[AuthorManager defaultManager] hasLoggedIn]) {
//        [[DataRequest sharedRequest] collectBook:[[AuthorManager defaultManager] userID]
//                                        username:[[AuthorManager defaultManager] username]
//                                          bookID:[self.bookInfo objectForKey:@"item_id"]];
//    } else {
//        AccountViewController *accountViewController = [[[AccountViewController alloc] initWithNibName:@"AccountViewController" bundle:nil] autorelease];
//        accountViewController.needLogin = YES;
//        [self.view.window.rootViewController presentViewController:accountViewController animated:YES completion:nil];
//    }
}

- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:self.view.bounds] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [coverImageView release];
    [artistLabel release];
    [chapterLabel release];
    [sharedLabel release];
    [collectedLabel release];
    [commentedLabel release];
    [rateView release];
    [rateLabel release];
    [descriptionTextView release];
    [_listenID release];
    [_listenInfo release];
    [_contentArray release];
    [downloadButton release];
    [shareButton release];
    [super dealloc];
}
- (void)viewDidUnload {
    [coverImageView release];
    coverImageView = nil;
    [artistLabel release];
    artistLabel = nil;
    [chapterLabel release];
    chapterLabel = nil;
    [sharedLabel release];
    sharedLabel = nil;
    [collectedLabel release];
    collectedLabel = nil;
    [commentedLabel release];
    commentedLabel = nil;
    [rateView release];
    rateView = nil;
    [rateLabel release];
    rateLabel = nil;
    [descriptionTextView release];
    descriptionTextView = nil;
    [downloadButton release];
    downloadButton = nil;
    [shareButton release];
    shareButton = nil;
    [super viewDidUnload];
}

@end
